<template>
  <a-modal
    :title="title"
    :width="720"
    :visible="visible"
    :confirmLoading="loading"
    @ok="_submit"
    @cancel="_cancel">
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['applyId', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item v-show="false" label="主键ID">
          <a-input v-decorator="['merchantId', { initialValue: 0 }]" disabled />
        </a-form-item>
        <a-form-item label="商店号">
          <a-input v-decorator="['merchantNo', { rules: [{ required: true, message: '商店号不能为空!' }] }]" />
        </a-form-item>
        <a-form-item label="商户名称">
          <a-input v-decorator="['merchantName', { rules: [{ required: true, message: '商户名称不能为空!' }] }]" />
        </a-form-item>
        <a-form-item label="商户联系人">
          <a-input v-decorator="['contactName', { rules: [{ required: true, message: '商户联系人不能为空!' }] }]" />
        </a-form-item>
        <a-form-item label="联系人手机号">
          <a-input
            :maxLength="11"
            v-decorator="['contactMobile', { rules: [{ required: true, message: '联系人手机号不能为空!' }] }]"
          />
        </a-form-item>
        <a-form-item label="客户经理">
          <a-select
            placeholder="请选择客户经理"
            v-decorator="['custMagerId', { rules: [{ required: true, message: '请选择客户经理,客户经理不能为空！' }] }]"
          >
            <a-select-option :value="item.custMagerId" v-for="item in custMagerSelList" :key="item.custMagerId">
              {{ item.userName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="还款方案">
          <a-select placeholder="请选择还款方案" v-decorator="['repaymentPlanId', { initialValue: '' }]" allowClear>
            <a-select-option
              :value="item.repaymentPlanId"
              v-for="item in repaymentPlanSelList"
              :key="item.repaymentPlanId"
            >
              {{ item.repaymentPlanName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="信用等级">
          <a-select placeholder="请选择信用等级" v-decorator="['creditLevel', { initialValue: '' }]" allowClear>
            <a-select-option value="A级">A级</a-select-option>
            <a-select-option value="B级">B级</a-select-option>
            <a-select-option value="C级">C级</a-select-option>
            <a-select-option value="D级">D级</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="图片">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :customRequest="customRequest"
            :remove="delFile"
            @preview="handlePreview"
            v-decorator="['pics', { initialValue: '' }]"
          >
            <div v-if="fileList.length < 8">
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { uploadFile, getRepaymentPlanSelList, getCustMagerSelList } from '@/api/common'
// 表单字段
const fields = [
  'applyId',
  'merchantId',
  'merchantNo',
  'merchantName',
  'contactName',
  'contactMobile',
  'custMagerId',
  'repaymentPlanId',
  'creditLevel',
  'pics'
]

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      uploadLoading: false,
      previewVisible: false,
      previewImage: '',
      fileList: [],
      repaymentPlanSelList: [],
      custMagerSelList: [],
      form: this.$form.createForm(this)
    }
  },
  methods: {
    /**
     * 提交表单
     */
    _submit: function () {
      this.$emit('ok')
    },
    /**
     * 取消
     */
    _cancel: function () {
      this.$emit('cancel')
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },

    customRequest (options) {
      const params = new FormData()
      this.uploadLoading = true
      params.append('file', options.file)
      params.append('uploadType', 'merchant')
      uploadFile(params).then((res) => {
        this.fileList
          .push({
            uid: this.fileList.length - 1,
            name: options.file.name,
            status: 'done',
            url: res.url
          })
          .catch((e) => {})
        this.form.setFieldsValue({
          pics: this.fileList.map((item) => item.url).join(',')
        })
        this.uploadLoading = false
      })
    },
    /**
     * 删除图片
     */
    delFile (options) {
      const curIndex = this.fileList.findIndex((item) => {
        return item.name === options.name
      })
      this.fileList.splice(curIndex, 1)
      this.form.setFieldsValue({
        pics: this.fileList.map((item) => item.url).join(',')
      })
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach((v) => this.form.getFieldDecorator(v))

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      this.fileList = []
      if (this.model) {
        if (this.model?.pics?.length) {
          const fileList = this.model.pics.split(',')
          console.log(fileList)
          this.fileList = fileList.map((val, idx) => {
            return {
              uid: idx + 1,
              name: `filename_${idx + 1}`,
              status: 'done',
              url: val
            }
          })
          console.log(this.fileList)
        }

        this.form.setFieldsValue(pick(this.model, fields))
      }
    })
  },
  mounted () {
    getRepaymentPlanSelList({})
      .then((res) => {
        this.repaymentPlanSelList = res.dataList
      })
      .catch((e) => {})
    getCustMagerSelList({})
      .then((res) => {
        this.custMagerSelList = res.custMagerList
      })
      .catch((e) => {})
  }
}
</script>
<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.bannerImg {
  width: 100%;
  height: 100%;
}
</style>
